
import 'ol/ol.css';

import Map from 'ol/Map.js';
import View from 'ol/View.js';
import Icon from 'ol/style/Icon';
import Style from 'ol/style/Style';
import Fill from 'ol/style/Fill';
import VectorSource from 'ol/source/Vector';
import VectorLayer from 'ol/layer/Vector';
import Point from 'ol/geom/Point';
import Polygon from 'ol/geom/Polygon';
import Feature from 'ol/Feature';
import Stroke from "ol/style/Stroke";
import hull from "./hull/hull";

const gen_igvConvex = () => [
    [0.0, 0.0],
    [0.0, 3.0],
    [15.0, 3.0],
    [15.0, 0.0],
    [0.0, 0.0],
];

const rotate_igvConvex = (vector2, heading) => {
    const X = vector2[0];
    const Y = vector2[1];
    vector2[0] = Math.cos(heading) * X - Math.sin(heading) * Y;
    vector2[1] = Math.sin(heading) * X + Math.cos(heading) * Y;
}

const initOpenlayers = (id) => {
    const map = new Map({ target: id });
    const view = new View({ projection: "EPSG:3857", center: [0.0, 0.0], zoom: 18.0 });
    map.setView(view);
    return { map, view };
}

export const initialize = (id) => {
    const { map, view } = initOpenlayers(id);
    const vectorSource = new VectorSource();
    const vectorLayer = new VectorLayer({ source: vectorSource });
    map.addLayer(vectorLayer);

    const igvConvex1 = gen_igvConvex();
    igvConvex1.forEach(item => {
        item[0] += 20.0;
        item[1] += 20.0;
    });
    const igvConvex2 = gen_igvConvex();
    igvConvex2.forEach(item => {
        rotate_igvConvex(item, -Math.PI / 12.0); // 先旋转
        // 再平移
        item[0] += 20.0;
        item[1] += 20.0;
        item[0] += 5.0;
    });
    const igvConvex3 = gen_igvConvex();
    igvConvex3.forEach(item => {
        rotate_igvConvex(item, -Math.PI / 6.0); // 先旋转
        // 再平移
        item[0] += 20.0;
        item[1] += 20.0;
        item[0] += 8.0;
        item[1] -= 1.0;
    });


    const igvConvexes = [igvConvex1, igvConvex2, igvConvex3];

    // 方式1
    igvConvexes.forEach(item => {
        const feature = new Feature();
        const polygon = new Polygon([item]);
        feature.setGeometry(polygon);
        const stroke = new Stroke({ color: "#FF0000FF", width: 1 });
        const style = new Style({ fill: new Fill({ color: "#FFFF00AA" }) });
        style.setStroke(stroke);
        feature.setStyle(style);

        vectorSource.addFeature(feature);
    });

    // 方式2
    const points = [];
    console.log(points);
    igvConvexes.forEach(convex => {
        convex.forEach(point => {
            points.push(point);
        });
    });
    const hulled = hull(points, Infinity);
    const feature = new Feature();
    const polygon = new Polygon([hulled]);
    feature.setGeometry(polygon);
    const stroke = new Stroke({ color: "#FF0000FF", width: 1 });
    const style = new Style({ fill: new Fill({ color: "#FFFF00AA" }) });
    style.setStroke(stroke);
    feature.setStyle(style);
    vectorSource.addFeature(feature);

}